﻿//ajax组件
var ajax = new Object();

ajax.$x = function(url,method,onload,onerror,postStr,relate,stateArray){
	this.url = url;
	this.req = null;
	this.method = method;
	this.onload = onload;
	this.postStr = postStr;
	this.onerror = (onerror) ? onerror : this.defaultError;
	this.relate = relate;
	this.stateNum = (stateArray) ? stateArray : false;
	this.loadXMLDoc();
}
ajax.$x.prototype = {
	loadXMLDoc:function(){
		if(window.XMLHttpRequest){
			this.req = new XMLHttpRequest();
			if(this.req.overrideMimeType){
					this.req.overrideMimeType('text/xml');
			}
		}else if(window.ActiveXObject){
		    var MSXML = ["Msxml3.XMLHTTP","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
		    for(var i=0, j=MSXML.length; i<j; i++){
		        try{
		            this.req = new ActiveXObject(MSXML[i]);
		            break;
		        }catch(e){}
		    }
		}
		if(this.req){
			try{
				var loader = this;
				this.req.onreadystatechange = function(){
					loader.onReadyState.call(loader)
				}
				this.req.open(this.method,this.url,true);
				this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
				this.req.send(this.postStr);
			}catch(err){
				this.onerror.call(this);
			}
		}
	},
	onReadyState:function(){
		var req = this.req;
		var ready = req.readyState;
		if(this.stateNum && ready >= 1 && ready <= 3){
			this.stateNum[ready-1].call(this);
		}else if(ready == 4){
			var httpStatus = req.status;
			if(httpStatus == 200 || httpStatus == 0){
				this.onload.call(this);
			}else{
				this.onerror.call(this);
			}
		}
	},
	defaultError:function(){
		alert("数据连接错误!"
			+ "\n\nreadyState: " + this.req.readyState
			+ "\nstatus: " + this.req.status
			+ "\nheafers: " + this.req.getAllResponseHeaders()
			)
	}
}